<template>
  <!--企业管理信息-->
  <el-row style="height:100%">
    <page @buttons="configPermissions">
      <pageheader :event="'enterprisePopUp'" :isShow="buttonPermissions.isAdd">企业管理</pageheader>
      <div class="page-content">
        <el-card class="box-card">
          <TreeTable
            class="pad_left_30table"
            :tableData="dataTable"
            :columns="columns"
            header-align="center"
            @enterpriseData="enterpriseData"
            @enterpriseDel="enterpriseDel"
            @link="link"
            :openRowName="'enterpriseOpenRow'"
            border>
          </TreeTable>
        </el-card>
        <el-dialog v-dialogDrag  :title="pageTitle" :visible.sync="isShow" @close="closeDialog('ruleForm')"
                   :modal-append-to-body="false" :close-on-click-modal="false" width="800px">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="企业名称" prop="company_name" >
              <el-input v-model="ruleForm.company_name" size="small" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="所属企业" prop="parent_id_arr">
              <Cascader :value.sync="ruleForm.parent_id_arr"
                        :options="options"
                        :changeEvent="'enterpriseChange'"
                        :width="'450px'"
                        :disabled="isDisabled"></Cascader>
            </el-form-item>
            <el-form-item label="企业描述" prop="company_desc">
              <el-input v-model="ruleForm.company_desc" type="textarea" size="small" :rows="3" style="width:450px"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button v-if="(!isDisabled && buttonPermissions.isAdd) || (isDisabled && buttonPermissions.isModify)"
              type="primary" size="small" @click="confirmDialog('ruleForm')">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
  }
</style>
<script>
import page from "@/components/page/page";
import pageheader from "@/components/page/pageheader";
import SearchInput from "@/components/sys/assembly/searchinput";
import Cascader from "@/components/sys/assembly/elcascader";
import TreeTable from "@/components/sys/assembly/treeTable";

export default {
  data() {
    let validateCompanyName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入企业名称'));
      } else {
        let str =  /[`~!@#$%^&*\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*\-+={}|《》？：“”【】、；‘’，。、]/im;
        if(str.test(value)){
          return callback(new Error('企业名称不得使用特殊符号！'));
        }
        if(value.length >=30){
          return callback(new Error('企业名称长度不能超过30个字！'));
        }
        callback();
      }
    };
    return {
      pageTitle: "企业管理信息",
      dataTable:[],//表格数据
      columns:[
        {
          text: "企业名称",
          value: "company_name",
          align: "left",

          // width: 200
        },
        {
          text: "序号",
          value: "",
          align: "center",
          width: 60
        },
        {
          text: "所属企业",
          value: "parent_id_str",
          align: "center",
          // width: 300
        },
        {
          text: "是否完成初始化",
          value: "is_init_str",
          align: "center",
          // width: 300
        },
        {
          text: "跳转案场",
          value: "",
          align: "center",
          button:[
            {
              name:'跳转案场',
              type:'text',
              event:'link',
            }
          ]
        },
        {
          text: "操作",
          value: "",
          align: "center",
          button:[]
        }
      ],//表头参数
      isShow: false,//是否显示模态框
      isDisabled:false,//是否是修改状态
      ruleForm: {
        company_name:'',//企业名称
        parent_name_list:[],//所属企业名称arr
        parent_id_arr:[],//所属企业arr
        parent_id:'',//所属企业str
        company_desc:'',//企业描述
        // company_address:'',//详细地址
        // provinceCode:'',//省
        // cityCode:'',//市
        // areaCode:'',//区
      },//模态框form表单
      rules: {
        company_name: [{ required: true, validator:validateCompanyName, trigger: "blur"}],
      },//form表单验证
      options:[],//级联控件 所属企业
      // provinceList:[],
      // cityList:[],
      // areaList:[],
      buttonPermissions:{
        isAdd:false,
        isDel:false,
        isModify:false,
        isWatch:false,
      },
      expandedRows:'',
    };
  },
  inject:['reload'],
  components: {
    page,
    pageheader,
    SearchInput,//搜索框组件
    Cascader,//级联选择器组件
    TreeTable,//表格组件
  },
  created() {
    this.expandedRows = new Set()
    //判断是否有按钮权限
    if(sessionStorage.buttonPermissions){
      this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
    }
    //初始化页面
    this.getTree()
  },
  mounted() {
    //新增按钮点击事件
    this.$Bus.$on("enterprisePopUp",() => {
      // this.isShow = true;
      // this.isDisabled = false;
      this.$router.push({name:'addEnterprise',params:{active:0}})
    });
    //级联change事件
    this.$Bus.$on("enterpriseChange", data => {
      this.ruleForm.parent_id_arr = data
      this.ruleForm.parent_id = data.slice(-1)[0]
    });
  },
  beforeDestroy() {
    //销毁Bus绑定事件
    this.$Bus.$off("enterprisePopUp");
    this.$Bus.$off("enterpriseChange");
  },
  watch: {},
  methods: {
    //配置按钮权限，根据权限不同调整表头渲染参数
    configPermissions(val){
      let buttonPermissions = val
      let menuButtonPermissions = [];//按钮权限数组
      let operation = {
        text: "操作",
        value: "",
        align: "center",
        button:[]
      };//操作
      buttonPermissions.forEach(e =>{
        for(let key in e){
          if(key == 'menu_code'){
            menuButtonPermissions.push(e[key])
          }
        }
      });
      this.buttonPermissions.isAdd = menuButtonPermissions.includes('enterAdd') ? true : false; //是否有新增权限
      this.buttonPermissions.isDel = menuButtonPermissions.includes('enterDelete') ? true : false; //是否有删除权限
      this.buttonPermissions.isModify = menuButtonPermissions.includes('enterModify') ? true : false; //是否有修改权限
      this.buttonPermissions.isWatch = menuButtonPermissions.includes('enterWatch') ? true : false; //是否有查看权限
      //查看和删除权限配置 当查看和删除权限都没有的时候则不push operation
      if(this.buttonPermissions.isWatch || this.buttonPermissions.isDel){
        if(this.buttonPermissions.isWatch){
          operation.button.push({
            name:'详情',
            type:'',
            event:'enterpriseData',
          },)
        }
        if(this.buttonPermissions.isDel){
          operation.button.push( {
            name:'删除',
            type:'danger',
            event:'enterpriseDel',
          },)
        }
      }
      this.columns.splice(-1,1,operation)
    },
    //获取企业tree
    getTree(){
      let url = '/sys/report_assist_new/company_tree';
      this.$api.get(url)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          console.log(data,'data');
          recursion(data.data);
          function recursion(val) {
            if(val.length){
              for(let i in val){
                val[i].value = val[i].id;
                val[i].label = val[i].company_name;
                val[i].is_init_str = val[i].step_status == 9 ? '是' : '否';
                val[i].parent_id_str = val[i].parent_name_list.join('/');
                if(val[i].children && val[i].children.length){
                  recursion(val[i].children)
                }else{
                  delete val[i].children
                }
              }
            }
          }
          this.dataTable = data.data
          this.options = data.data
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //关闭模态框
    closeDialog(formName){
      this.$refs[formName].resetFields();
      this.$Bus.$emit('Loading',false)
    },
    //修改按钮点击事件
    enterpriseData(data){
      let step_status = data.step_status
      if(step_status ==9){
        this.isShow = true;
        this.isDisabled = true;
        this.getCompany(data.id)
      }else{
        this.$router.push({name:'addEnterprise',params:{active:step_status,id:data.id,company_name:data.company_name}})
      }

    },
    //获取企业查看详情
    getCompany(id){
      let url = '/sys/company/get?id=' + id
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          let list = data.data
          list.parent_id_arr = list.node_location.split('-');
          list.parent_id_arr.splice(-2,2);
          this.ruleForm = Object.assign(this.ruleForm,list)
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //模态框保存按钮
    confirmDialog(formName) {
      let data = {};
      let model = null;
      let url = ''
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$Bus.$emit('Loading',true)
          model = this.$refs[formName].model;
          if (this.isDisabled) {
            data.company_desc = model.company_desc
            data.company_name = model.company_name
            url = "sys/company/update?id=" + model.id;
            this.modifyCompany(url, data);
          } else {
            data.company_desc = model.company_desc
            data.company_name = model.company_name
            data.parent_id = model.parent_id
            url = "sys/company/add";
            this.addCompany(url, data);
          }
        } else {
          console.log("error submit!!");
          return;
        }
      });
    },
    //新增保存
    addCompany(url, data) {
      this.$api
      .post(url, data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.$api.get('/sys/report_assist_new/refresh_auth_cache')
          .then(data=>{}).catch(err=>{ console.log(err);})
          this.reload();
          this.$message({
            message: "新增成功",
            type: "success"
          });
        }
        this.$Bus.$emit('Loading',false)
      })
    },
    //修改保存
    modifyCompany(url,data){
      this.$api
      .put(url, data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.$api.get('/sys/report_assist_new/refresh_auth_cache')
          .then(data=>{}).catch(err=>{ console.log(err);})
          this.reload();
          this.$message({
            message: "修改成功",
            type: "success"
          });
        }
        this.$Bus.$emit('Loading',false)
      })
    },
    //级联change事件
    enterpriseChange(data){
      this.ruleForm.parent_id_arr = data
      this.ruleForm.parent_id = data.slice(-1)[0]
    },
    //删除按钮点击事件
    enterpriseDel(data){
      if(data.children){
        this.$message.error('该企业下包含子企业，不能进行删除操作')
      }else{
        this.$confirm("是否删除‘"+ data.company_name +"’？",'提示', {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center:true
        })
        .then(() => {
          this.$Bus.$emit('Loading',true)
          this.delData(data.id);
        })
        .catch(() => {});
      }
    },
    //删除接口
    delData(id) {
      let url = "sys/company/del/";
      let data = {
        id:id
      }
      this.$api
      .delete(url,data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.reload();
          this.$message({
            message: "删除成功",
            type: "success"
          });
        }
        this.$Bus.$emit('Loading',true)
      })
    },

    //跳转案场
    link(data){
      if(data.step_status == 9){
        // localStorage.active = toName
        this.$router.push({ name: 'mallmanager', query: { id: data.node_location }});
      }else{
        this.$message('企业初始化未完成不能跳转案场！')
      }

    }
  },
};
</script>
